package cn.tedu.ivos.geofence.service.impl;

import cn.tedu.ivos.base.exception.ServiceException;
import cn.tedu.ivos.base.response.StatusCode;
import cn.tedu.ivos.geofence.mapper.GeofenceMapper;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceParam;
import cn.tedu.ivos.geofence.pojo.dto.GeofenceQuery;
import cn.tedu.ivos.geofence.pojo.entity.Geofence;
import cn.tedu.ivos.geofence.pojo.vo.GeofenceVO;
import cn.tedu.ivos.geofence.service.GeofenceService;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class GeofenceServiceImpl implements GeofenceService {
    @Autowired
    GeofenceMapper geofenceMapper;
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<GeofenceVO> selectGeofence(GeofenceQuery geofenceQuery){
        log.debug("查询围栏业务:geofenceQuery={}",geofenceQuery);
        List<GeofenceVO> list = geofenceMapper.selectGeofence(geofenceQuery);
        return list;
    }

    @Override
    public void saveGeofence(GeofenceParam geofenceParam) {
        log.debug("保存围栏业务:geofenceParam={}",geofenceParam);
        Geofence geofence = new Geofence();
        BeanUtils.copyProperties(geofenceParam,geofence);
        if (geofence.getId() != null){
            geofence.setUpdateTime(new Date());
            geofenceMapper.update(geofence);
        }else {
            geofence.setStatus("1"); //启用
            geofence.setCreateTime(new Date());
            geofenceMapper.insert(geofence);
        }
    }

    @Override
    public void deleteGeofence(Long id) {
        log.debug("删除围栏业务:id={}",id);
        //业务：需要判断该围栏上是否有绑定车辆，如果有绑定车辆，就不能删除！
        //1.封装查询车辆的DTO层对象
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setGeofenceId(id);
        //2.调用车辆模块的车辆查询方法，查询指定围栏下的所有车辆数据
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        //3.判断车辆列表，如果该围栏下有车辆，业务层需要抛出操作失败的异常
        if(list.size()>0 && list != null){
            throw new ServiceException(StatusCode.OPERATION_FAILED);
        }else {
            geofenceMapper.deleteById(id);
        }
    }
}



